import md5 from './md5.js';

const apis = {
  code2session: "/api/wechat/user/code2session",
  decryptUserInfo: "/api/wechat/user/doLogin",
  getUserPhone: "/api/wechat/user/getUserPhone",

  //index apis
  getIndexData: "/api/index/data",

  //user apis
  userInfo: "/api/user",
  myInfo: "/api/user/me",
  userSave: "/api/user/save",
  getUserAmount: "/api/user/getUserAmount",
  getUserIndexData: "/api/index/ucenter",

  //article apis
  articleInfo: "/api/article",
  articleList: "/api/article/list",
  articleRelevantList: "/api/article/relevantList",
  articlePagination: "/api/article/paginate",
  articleCategoryInfo: "/api/article/category",
  articleCategories: "/api/article/categories",
  articleSave: "/api/article/save",
  tagArticleList:"/api/article/tagArticles",

  //comment
  commentPaginate:"/api/article/commentPaginate",
  postComment: "/api/article/postComment",

  //page apis
  pageInfo: "/api/page",
  pageList: "/api/page/list",

  //option apis
  optionInfo: "/api/option",

  //others
  html2wxml:"/commons/html2wxml",

  //articleMeta plugin
  articleMeta : "/articlemeta/api",

  //product api
  productInfo: "/api/product/detail",
  productList: "/api/product/list",
  searchProduct: "/api/product/productSearch",
  getNewProductList: "/api/product/getNewProductList",
  getRecommendProductList: "/api/product/getRecommendProductList",
  getProductCategory: "/api/category/get",
  getProductCategroyList: "/api/category/list",
  getProductPageList: "/api/product/page",
  getProductListByTag: "/api/product/listByTag",

  //address api
  addressList: "/api/address/list",
  delAddress: "/api/address/doDelete",
  addAddress: "/api/address/doSave",
  getAddress: "/api/address/get",
  getDefaultAddress: "/api/address/getDefault",

  //cart api
  cartList: "/api/usercar",
  add2Cart: "/api/usercar/doAddCar",
  del2Cart: "/api/usercar/doDelCar",
  cartBalance: "/api/usercar/doBalance",

  //checkout api
  checkoutList: "/api/checkout",

  //order api
  createOrder: "/api/order/doCreateOrder",
  payOrder: "/api/pay/wechat/mini",
  payOrder4Amount: "/api/pay/amount",
  orderList: "/api/order/page",
  orderDetail: "/api/order/detail",
  cancelOrder: "/api/order/doCancel",
  confirmDelivery: "/api/order/doConfirmDelivery",
  getOrderPostageFee: "/api/order/getPostageFee",

  //product comment api
  submitProductComment: "/api/product/comment/doSave",
  getUserProductCommentListByOrder: "/api/product/comment/getListByOrder",
  getProductCommentStatCount: "/api/product/comment/stat/count",
  pageProductCommentByProductId: "/api/product/comment/page",

  //usercoupon api
  getUserCouponList: "/api/coupon/getUserCouponList",
  getCouponList: "/api/coupon/getCouponList",
  takeCoupon: "/api/coupon/doTake",

  //member api
  getMemberInfoList: "/api/member/list",
  doJoinMember: "/api/member/doJoining",
  getMemberDetail: "/api/member/detail",

  //store api
  getStoreList: "/api/store/list",
  getStoreInfo: "/api/store/get",

}

const config = {
  host: "",
  app_id: "",
  app_secret: "",
  sessionId: "",
  jwt: ""
}

const init = conf => {
  config.host = conf.host;
  config.app_id = conf.app_id;
  config.app_secret = conf.app_secret;

  if(typeof(wx) != 'undefined'){
    var jwt = wx.getStorageSync("jwt");
    if(jwt){config.jwt = jwt}
  }
}

const getUrl = (api, paras) => {

  paras = Object.assign({
    appId: config.app_id,
    t: new Date().getTime()
  }, paras);

  //对数据进行签名
  var signString = sign(paras);

  //添加签名结果
  paras = Object.assign({
    sign: signString
  }, paras);

  //拼接URL地址
  var url = config.host + api + "?"
  var arr = Object.keys(paras);
  for (var i in arr) {
    url = url + (arr[i] + "=" + paras[arr[i]]) + "&";
  }
  //remove last '&'
  return url.substring(0, url.length - 1);
}

const createGetRequest = req => {
  //default is get
  return createRequest(req);
}

const createPostRequest = req => {
  return createRequest(Object.assign({ method: 'POST'}, req));
}

const createRequest = (req = {
  api,
  paras,
  method,
  header,
  data,
}) => {

 var url = getUrl(req.api,req.method == 'POST' ? {} : req.paras)

  var realRequest = {
    url: url,
    method: (req.method == null ? 'GET' : req.method),
    header: Object.assign({ "Jwt": config.jwt }, req.header),
    data: req.data 
  }

  const p = new Promise((resolve, reject) => {

    function start(resolve,reject){
        var requestHandler;

            //支持微信小程序
            if(typeof(wx) != 'undefined'){
                requestHandler = wx;
            }
            //支持百度小程序
            else if(typeof(swan) != 'undefined'){
                requestHandler = swan;
            }

            requestHandler.showLoading({
              title: '加载中...',
            })
            requestHandler.request(Object.assign({
            success: function (res) {
                requestHandler.hideLoading()
                //注意：第一个字母大写
                if (res.header.Jwt){
                    updateJwt(res.header.Jwt);
                }
                if (res.data.code == 1) {
                  resolve(res.data.data);
                } else if(res.data.code == 999){
                  //登录失效，移除登录态
                  wx.removeStorageSync('jwt');
                  wx.removeStorageSync('userInfo');
                  wx.setStorageSync('isLogin', false);
                  wx.navigateTo({
                    url: '/pages/auth/tologin/tologin',
                  })
                }
                else {
                  reject(res);
                }
                
            },
            error:function(e){
                reject({
                    code: 98,
                    message: 'error, ' + e.errMsg
                });
            },
            fail: function (e) {
                reject({
                    code: 99,
                    message: 'fail, ' + e.errMsg
                });
            }}, realRequest))
    } 

    start(resolve, reject)
   
  }).catch(error =>{
    wx.showToast({
      icon: 'none',
      title: error && error.data ? error.data.message : error.message ? error.message : "系统错误",
    })
  });

  return {
    send: () => p
  }
}

/**
 * 对 obj 进行签名，返回签名内容
 * 要保证和jeegot签名算法一致
 */
const sign = obj => {

  var secret = config.app_secret;

  //生成key升序数组，与jeegot后台保存一致
  var arr = Object.keys(obj);
  arr.sort();

  var str = '';
  for (var i in arr) {
    var value = obj[arr[i]];
    if(value ==0 || value ==1){
      str += arr[i] +value.toString();
    }else {
      if(value) str += arr[i] +value.toString();
    }
    
  }

  return md5(str + secret);
}

const code2session = code => {

  createRequest({
    api: apis.code2session,
    paras: { code: code }
  })
  .send()
  .then(data => {
    config.sessionId = data.sessionId;
    wx.setStorage({
      key: 'sessionId',
      data: config.sessionId
    })
    return true;
  })
  .catch(data => {
    return false;
  })
}

const updateJwt = value => {
  config.jwt = value;
  wx.setStorage({
    key: 'jwt',
    data: value,
  })
}

const decryptUserInfo =  (data = {
  rawData, signature, encryptedData, iv
},callback) => {

  //用户拒绝授权的情况
  if(data.rawData == undefined) return

  createPostRequest({
    api: apis.decryptUserInfo,
    data: Object.assign({ sessionId: config.sessionId }, data)
  })
  .send()
  .then(data => {
    updateJwt(data);
    if (callback) callback(true);
  })
  .catch(data => {
    if (callback) callback(false);
  })

}

const getUserPhone =  (data = {
  encryptedData, iv
},callback) => {

  //用户拒绝授权的情况
  if(data.encryptedData == undefined) return

  let sessionId = wx.getStorageSync('sessionId')
  
  createPostRequest({
    api: apis.getUserPhone,
    data: Object.assign({ sessionId: sessionId }, data)
  })
  .send()
  .then(data => {
    wx.setStorage({
      key: 'phone',
      data: data,
    })
    if (callback) callback(true);
  })
  .catch(data => {
    if (callback) callback(false);
  })

}

//////////////////////index api start /////////////////////////////////
const getIndexData = (paras={}) => {
  return createGetRequest({
    api: apis.getIndexData,
    paras: paras
  }).send()
}
//////////////////////index api end ////////////////////////////////////

///////////////////////option api start/////////////////////////////////

/**
 * 获取网站配置信息
 */
const getOption = (paras={key}) => {
  return createGetRequest({
    api: apis.optionInfo,
    paras: paras
  }).send()
}

const getAppName = () => {
  return getOption({key: 'wechat_miniprogram_name'})
}

const getCopyright = () => {
  return getOption({key: 'wechat_miniprogram_copyright'})
}

const getSlides = () => {
  return getOption({key: 'wechat_miniprogram_slides'})
}

///////////////////////option api end/////////////////////////////////

///////////////////////user api start/////////////////////////////////

/**
 * 获取用户信息
 */
const getUser = (paras={id}) => {
  return createGetRequest({
    api: apis.userInfo,
    paras: paras
  }).send()
}

/**
 * 获取登录用户信息（我的信息）
 */
const getMyInfo = () => {
  return createGetRequest({
    api: apis.myInfo
  }).send()
}

/**
 * 用户信息保存
 */
const doUserSave = userData => {
  return createPostRequest({
    api: apis.userSave,
    data: userData,
  }).send()
}

/**
 * 获取用户账户余额
 */
const getUserAmount = () => {
  return createGetRequest({
    api: apis.getUserAmount
  }).send()
}

const getUserIndexData = () => {
  return createGetRequest({
    api: apis.getUserIndexData
  }).send()
}

///////////////////////user api end/////////////////////////////////


///////////////////////article api start/////////////////////////////////

/**
 * 获取文章信息
 */
const getArticle = (paras={id}) => {
  return createGetRequest({
    api: apis.articleInfo,
    paras: paras
  }).send()
}

/**
 * 获取文章列表
 */
const getArticleList = (paras = {
  flag,
  hasThumbnail,
  orderBy,
  count
}) => {
  return createGetRequest({
    api: apis.articleList,
    paras: paras
  }).send()
}


/**
 * 获取文章的相关文章
 */
const getArticleRelevantList = (paras = {articleId,count}) => {
  return createGetRequest({
    api: apis.articleRelevantList,
    paras: paras
  }).send()
}


/**
 * 分页获取文章内容
 */
const getArticlePage = (paras = {
  categoryId,
  orderBy,
  pageNumber,
}) => {
  return createGetRequest({
    api: apis.articlePagination,
    paras: paras
  }).send()
}

/**
 * 获取文章分类信息
 */
const getArticleCategory = (paras = {
  id,
  slug,
  type,
}) => {
  return createGetRequest({
    api: apis.articleCategoryInfo,
    paras: paras
  }).send()
}

/**
 * 获取文章分类信息
 */
const getArticleCategories = (paras={
    type,
    pid
}) => {
  return createGetRequest({
    api: apis.articleCategories,
    paras: paras
  }).send()
}


const getTagArticleList = (paras = {
  tag,
  count,
}) => {
  return createGetRequest({
    api: apis.tagArticleList,
    paras: paras
  }).send()
}

/**
 * 保存文章
 */
const doArticleSave = articleData => {
  return createPostRequest({
    api: apis.articleSave,
    data: articleData,
  }).send()
}


const getCommentPage = (paras = {
  articleId,
  page
}) => {
  return createGetRequest({
    api: apis.commentPaginate,
    paras: paras
  }).send()
}

/**
 * 发布评论
 */
const doPostComment = (paras = {
  articleId,
  pid
},content) => {
  return createPostRequest({
    api: apis.postComment,
    paras: paras,
    data: content,
  }).send()
}

///////////////////////article api end/////////////////////////////////


///////////////////////page api start/////////////////////////////////

/**
 * 获取页面信息
 */
const getPage = (paras = {
    id,
    slug,
}) => {
  return createGetRequest({
    api: apis.pageInfo,
    paras: paras
  }).send()
}

/**
 * 获取页面列表
 */
const getPageList = (paras={
    flag:flag
}) => {
  return createGetRequest({
    api: apis.pageList,
    paras: paras
  }).send()
}

///////////////////////page api end/////////////////////////////////

const isLogined = () => {
  return config.jwt != "";
}

const html2wxml = data => {
  return createPostRequest({
    api: apis.html2wxml,
    header: {
        'content-type': 'application/x-www-form-urlencoded'
    },
    data:data
  }).send()
}

/////////////////article meta plugin ////////

const getArticleMeta = (paras={articleId,fieldNames}) => {
  return createGetRequest({
    api: apis.articleMeta,
    paras: paras
  }).send()
}


///////////////////////article meta plugin end//////////////////////////



///////////////// product api start /////////////////

/**
 * 获取产品内容
 */
const getProduct = (paras = { id }) => {
  return createGetRequest({
    api: apis.productInfo,
    paras: paras
  }).send()
}

/**
 * 获取产品列表
 */
const getProductList = (paras = {
  flag,
  hasThumbnail,
  orderBy,
  count
}) => {
  return createGetRequest({
    api: apis.productList,
    paras: paras
  }).send()
}

/**
 * 获取首页新上架商品列表
 */
const getNewProductList = (paras = {
}) => {
  return createGetRequest({
    api: apis.getNewProductList,
    paras: paras
  }).send()
}

/**
 * 获取首页推荐商品列表
 */
const getRecommendProductList = (paras = {
}) => {
  return createGetRequest({
    api: apis.getRecommendProductList,
    paras: paras
  }).send()
}

/**
 * 根据产品名称模糊搜索产品
 */
const searchProduct = (paras = {keyword}) =>{
  return createGetRequest({
    api: apis.searchProduct,
    paras: paras
  }).send()
}

/**
 * 获取产品分类
 */
const getProductCategroyList = (paras = {
}) =>{
  return createGetRequest({
    api: apis.getProductCategroyList,
    paras: paras
  }).send()
}

/**
 * 获取当个产品分类
 * @param {*} paras 
 */
const getProductCategroy = (paras = {
  categoryId
}) =>{
  return createGetRequest({
    api: apis.getProductCategory,
    paras: paras
  }).send()
}

/**
 * 根据产品分类分页获取商品
 */
const getProductPageList = (paras ={categoryId, page, size}) => {
  return createGetRequest({
    api: apis.getProductPageList,
    paras: paras
  }).send()
}

const getProductListByTag = (paras ={tag}) => {
  return createGetRequest({
    api: apis.getProductListByTag,
    paras: paras
  }).send()
}

/////////////// product api end /////////////////

///////////////// address api start /////////////////

/**
 * 获取地址列表
 */
const getAddressList = (paras = {}) => {
  return createGetRequest({
    api: apis.addressList,
    paras: paras
  }).send()
}

/**
 * 删除一个地址
 */
const delAddress = (paras = {id}) => {
  return createGetRequest({
    api: apis.delAddress,
    paras: paras
  }).send()
}

/**
 * 添加或修改地址
 * @param {*} paras 
 */
const addAddress = addressData => {
  return createPostRequest({
    api: apis.addAddress,
    data: addressData
  }).send()
}

/**
 * 查找用户默认地址
 */
const getDefaultAddress = (paras = {}) => {
  return createGetRequest({
    api: apis.getDefaultAddress,
    paras: paras
  }).send()
}

const getAddress = (paras = {id}) => {
  return createGetRequest({
    api: apis.getAddress,
    paras: paras
  }).send()
}

///////////////// address api end /////////////////

///////////////// cart api start /////////////////

/**
 * 获取用户购物车列表数据
 */
const getCartList = (paras = {}) => {
  return createGetRequest({
    api: apis.cartList,
    paras: paras
  }).send()
}

/**
 * 添加到购物车
 */
const add2Cart = cartData => {
  return createPostRequest({
    api: apis.add2Cart,
    data: cartData
  }).send()
}

/**
 * 删除购物车里面一个商品
 */
const del2Cart = (paras = {id}) => {
  return createGetRequest({
    api: apis.del2Cart,
    paras: paras
  }).send()
}

/**
 * 结算数据列表
 */
const checkoutList = (paras = {id}) => {
  return createGetRequest({
    api: apis.checkoutList,
    paras: paras
  }).send()
}

/**
 * 购物车提交结算
 */
const cartBalance = cartData => {
  return createPostRequest({
    api: apis.cartBalance,
    data: cartData
  }).send()
}

///////////////// cart api end /////////////////

///////////////// order api start /////////////////

/**
 * 创建订单
 */
const createOrder = (orderData) => {
  return createPostRequest({
    api: apis.createOrder,
    data: orderData
  }).send()
}

/**
 * 发起订单微信支付
 */
const payOrder = (paras = {orderId}) => {
  return createRequest({
    api: apis.payOrder,
    paras: paras
  }).send()
}

/**
 * 使用账户余额进行支付
 */
const payOrder4Amount = (payData) => {
  return createPostRequest({
    api: apis.payOrder4Amount,
    data: payData
  }).send()
}

const getOrderList = (paras = {title, sn, payStatus, shipStatus, tradeStatus}) => {
  return createGetRequest({
    api: apis.orderList,
    paras: paras
  }).send()
}

const getOrderDetail = (paras = {orderId}) => {
  return createGetRequest({
    api: apis.orderDetail,
    paras: paras
  }).send()
}

const cancelOrder = (paras = {orderId}) => {
  return createRequest({
    api: apis.cancelOrder,
    paras: paras
  }).send()
}

const confirmDelivery = (paras = {orderId}) => {
  return createRequest({
    api: apis.confirmDelivery,
    paras: paras
  }).send()
}

const getOrderPostageFee = (paras = {postageFee}) => {
  return createPostRequest({
    api: apis.getOrderPostageFee,
    data: paras
  }).send()
}

///////////////// order api end /////////////////

///////////////// product comment api begin /////////////////

const submitProductComment = (commentData) => {
  return createPostRequest({
    api: apis.submitProductComment,
    data: commentData
  }).send()
}

const getUserProductCommentListByOrder = (paras = {orderId}) => {
  return createRequest({
    api: apis.getUserProductCommentListByOrder,
    paras: paras
  }).send()
}

const getProductCommentStatCount = (paras = {productId}) => {
  return createRequest({
    api: apis.getProductCommentStatCount,
    paras: paras
  }).send()
}

const pageProductCommentByProductId= (paras ={productId, type, page, size}) => {
  return createGetRequest({
    api: apis.pageProductCommentByProductId,
    paras: paras
  }).send()
}

///////////////// product comment api end /////////////////

///////////////// usercoupon api start /////////////////

/**
 * 获取用户优惠券列表
 */
const getUserCouponList = (paras = {}) => {
  return createGetRequest({
    api: apis.getUserCouponList,
    paras: paras
  }).send()
}

/**
 * 获取用户可用优惠券列表
 */
const getCouponList = (paras = {}) => {
  return createGetRequest({
    api: apis.getCouponList,
    paras: paras
  }).send()
}

/**
 * 领取优惠券
 */
const takeCoupon = (paras = {couponId}) => {
  return createRequest({
    api: apis.takeCoupon,
    paras: paras
  }).send()
}

///////////////// usercoupon api end /////////////////

///////////////// member api start /////////////////

/**
 * 获取会员信息列表
 */
const getMemberInfoList = (paras = {}) => {
  return createGetRequest({
    api: apis.getMemberInfoList,
    paras: paras
  }).send()
}

const getMemberDetail = (paras = {}) => {
  return createGetRequest({
    api: apis.getMemberDetail,
    paras: paras
  }).send()
}

/**
 * 加入会员
 */
const doJoinMember = (memberData) => {
  return createPostRequest({
    api: apis.doJoinMember,
    data: memberData
  }).send()
}

///////////////// member api end /////////////////

//////////////// store api start /////////////////

/**
 * 获取门店分页列表 
 */
const getStoreList = (paras = {page,size}) => {
  return createGetRequest({
    api: apis.getStoreList,
    paras: paras
  }).send()
}

/**
 * 获取单个门店详细信息
 */
const getStoreInfo = (paras = {id}) => {
  return createGetRequest({
    api: apis.getStoreInfo,
    paras: paras
  }).send()
}

//////////////// store api end  //////////////////

const processImageSrcs = (paras={
    data,
    attrs
}) => {

  if(! paras.data ){
      return paras.data;
  }

  const attrs = paras.attrs ? paras.attrs.split(',') : null;

  if(paras.data instanceof Array){
    for (const index in paras.data) {
       const val = processObjImageSrcs(paras.data[index],attrs);
       if(val) paras.data[index] = val;
    }
  }
  //非数组的情况：object
  else{
     const val =  processObjImageSrcs(paras.data,attrs);
     if(val) paras.data = val;
  } 

  return paras.data;
}

const processObjImageSrcs = (obj,attrs)=>{
    if(typeof(obj) === 'string'){
        if(obj.indexOf('/') == 0){
           return config.host + obj;
        }
    }else{
        const arr = Object.keys(obj);
        for(const field in arr){
            for(const f in attrs){
                if(attrs[f] === arr[field]){
                    const value = obj[arr[field]];
                    if(value && value.indexOf('/') == 0){
                        obj[attrs[f]] = config.host + value;
                    }
                }
            }
        }
    }
}


module.exports = {
  config: config,
  getUrl:getUrl,
  html2wxml:html2wxml,
  processImageSrcs:processImageSrcs,

  init: init, //初始化
  createGetRequest: createGetRequest, //构建一个Get API请求
  createPostRequest: createPostRequest, //构建一个Post API请求
  createRequest: createRequest, //构建一个API请求，默认是get请求
  wxLogin: code2session, //进行用户code初始化
  wxGetUserInfo: decryptUserInfo, //进行用户注册 或 初始化当前用户信息
  getUserPhone: getUserPhone,     //获取用户手机号码
  isLogined: isLogined,

  //首页数据//
  getIndexData: getIndexData,

  // 配置相关 //
  getOption: getOption,
  getAppName: getAppName,
  getCopyright: getCopyright,
  getSlides: getSlides,
 

  // 用户相关 //
  getUser: getUser,
  getMyInfo: getMyInfo,
  doUserSave: doUserSave,
  getUserAmount: getUserAmount,
  getUserIndexData: getUserIndexData,

  // 文章相关 //
  getArticle: getArticle,
  getArticleList: getArticleList,
  getArticleRelevantList:getArticleRelevantList,
  getArticlePage: getArticlePage,
  getArticleCategory: getArticleCategory,
  getArticleCategories: getArticleCategories,
  getTagArticleList:getTagArticleList,
  doArticleSave: doArticleSave,
  doPostComment: doPostComment,
  getCommentPage: getCommentPage,

  // 页面相关 //
  getPage: getPage,
  getPageList: getPageList,


  // 产品相关 //
  getProduct: getProduct,
  getProductList: getProductList,
  searchProduct: searchProduct,
  getRecommendProductList: getRecommendProductList,
  getNewProductList: getNewProductList,
  getProductCategroyList: getProductCategroyList,
  getProductCategroy: getProductCategroy,
  getProductPageList: getProductPageList,
  getProductListByTag: getProductListByTag,

  // 地址相关 //
  getAddressList: getAddressList,
  delAddress: delAddress,
  addAddress: addAddress,
  getAddress: getAddress,
  getDefaultAddress: getDefaultAddress,

  //购物车相关
  getCartList: getCartList,
  del2Cart: del2Cart,
  add2Cart: add2Cart,
  cartBalance: cartBalance,

  //商品结算
  checkoutList: checkoutList,

  //订单相关
  createOrder: createOrder,
  payOrder: payOrder,
  payOrder4Amount: payOrder4Amount,
  getOrderList: getOrderList,
  getOrderDetail: getOrderDetail,
  cancelOrder: cancelOrder,
  confirmDelivery: confirmDelivery,
  getOrderPostageFee: getOrderPostageFee,

  //商品评论相关
  submitProductComment: submitProductComment,
  getUserProductCommentListByOrder: getUserProductCommentListByOrder,
  pageProductCommentByProductId: pageProductCommentByProductId,
  getProductCommentStatCount: getProductCommentStatCount,

  //优惠券相关
  getUserCouponList: getUserCouponList,
  getCouponList: getCouponList,
  takeCoupon: takeCoupon,

  //会员相关
  getMemberInfoList: getMemberInfoList,
  getMemberDetail: getMemberDetail,
  doJoinMember: doJoinMember,

  //门店相关
  getStoreList: getStoreList,
  getStoreInfo: getStoreInfo,

  getArticleMeta:getArticleMeta
  
}
